<?php
/**
 * Created by PhpStorm.
 * User: 76683
 * Date: 2018/7/21
 * Time: 9:00
 */

namespace app\api\model;


use think\Model;

class WeLikes extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * 热门话题
     * @param $time
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function hotId($time)
    {
        $data = self::where(['create_time' => ['>=', $time]])
            ->field('topic_id,count(*) as num')
            ->orderRaw('count(*) desc')
            ->group('topic_id')
            ->fetchSql(false)
            ->find();
        return empty($data) ? [] : $data->toArray();
    }

    public static function vote($data)
    {
        $exists = self::where($data)->fetchSql(false)->find();
        if (!empty($exists)) {
            if ($exists->is_delete == 0) {
                return ['code' => 0, 'msg' => '已点过赞了'];
            } else if ($exists->is_delete == 1) {
                $result = $exists->save(['is_delete' => 0]);
                WeTopic::where(['id' => $data['topic_id'], 'is_delete' => 0, 'status' => 1])->setInc('likes', 1);
                return $result;
            }
        }

        $res = self::create($data);
        //点赞数+1
        WeTopic::where(['id' => $data['topic_id'], 'is_delete' => 0, 'status' => 1])->setInc('likes', 1);
        return $res;
    }

    public static function cancelVote($data)
    {
        $res = self::where($data)->find();
        if (empty($res)) {
            return ['code' => 0, 'msg' => '未点赞过该话题'];
        } else {
            //点赞数-1
            $res->save(['is_delete' => 1]);
            WeTopic::where(['id' => $data['topic_id'], 'is_delete' => 0, 'status' => 1])->setInc('likes', -1);
            return $res;
        }

    }
}